<template>
  <div class="app-container">
    <div class="table_container">
      <div class="table_top_btn">
        <div class="left_btn">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="openAddOrEdit(['InventoryCheck', 'add'], {})"
            >{{ t("button.add") }}</el-button
          >
          <exportButton
            :columns="columns"
            :data="InventoryCheckData"
            :filename="`盘点数据(${getNowDate()})`"
          ></exportButton>
        </div>

        <right-toolbar
          ref="rightToolBarRef"
          @queryTable="queryList"
          :searchConfig="searchConfig"
          :columns.sync="columns"
          @search="handleSearch"
        >
        </right-toolbar>
      </div>

      <div class="table_area">
        <el-table
          height="100%"
          v-loading="loading"
          :data="InventoryCheckData"
          :header-cell-style="{ textAlign: 'center' }"
          :cell-style="{ textAlign: 'center' }"
        >
          <el-table-column
            :label="t('tableColumns.operation')"
            align="center"
            fixed
            width="150"
          >
            <template #default="{ row }">
              <div class="operate_link_btn">
                <el-link
                  type="success"
                  :underline="false"
                  :icon="Finished"
                  :disabled="
                    row.enableFlag != 0 ||
                    row.createUserId != JSON.parse(getUserInfo()).userId
                  "
                  @click="finishInventoryCheck(row)"
                  >{{ t("button.compete") }}</el-link
                >

                <el-link
                  type="danger"
                  :underline="false"
                  :icon="Delete"
                  @click="revokeReceive(row)"
                  :disabled="
                    row.enableFlag != 0 ||
                    row.createUserId != JSON.parse(getUserInfo()).userId
                  "
                  >{{ t("button.void") }}</el-link
                >
              </div>
            </template>
          </el-table-column>
          <template v-for="(item, index) in columns" :key="item.key">
            <el-table-column
              v-if="item.visible"
              :prop="item.prop"
              :label="t(`tableColumns.${item.langKey}`)"
              :width="item.width"
              :show-overflow-tooltip="true"
            >
              <template #default="{ row }">
                <div
                  v-if="item.prop == 'takeStockNo'"
                  :style="{
                    color: colors.primaryColor,
                    cursor: item.isclick ? 'pointer' : '',
                  }"
                  @click="openAddOrEdit(['receive', 'detail'], row)"
                >
                  {{ row.takeStockNo }}
                </div>

                <el-tag
                  v-else-if="item.prop == 'enableFlag'"
                  :type="
                    row.enableFlag == 0
                      ? 'warning'
                      : row.enableFlag == 1
                      ? 'success'
                      : 'danger'
                  "
                >
                  {{
                    filterStatus(
                      row.enableFlag,
                      "InventoryCheckStatus",
                      "id",
                      "langKey"
                    ) || "无"
                  }}
                </el-tag>
                <span
                  v-else-if="
                    item.prop == 'startDate' ||
                    item.prop == 'endDate' ||
                    item.prop == 'createDate'
                  "
                >
                  {{ parseTime(row[item.prop], "{y}-{m}-{d}") || "无" }}
                </span>
                <span v-else>{{ row[item.prop] || "无" }}</span>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </div>
      <div class="pagination-area">
        <pagination
          :total="page.total"
          v-model:page="page.pageNum"
          v-model:limit="page.pageSize"
          @pagination="queryList"
        />
      </div>
      <addOrEditDialog
        v-if="operate.openObj.visible"
        ref="addOrEditDialogRef"
        :operate="operate"
        @submitAddOrEdit="submit"
        @cancelAddOrEdit="cancel"
        @queryDetailList="queryInventoryCheckDetail"
      ></addOrEditDialog>
    </div>
  </div>
</template>

<script setup>
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import colors from "@/assets/styles/variables.module.scss";
import { Finished, Delete } from "@element-plus/icons-vue";
import RightToolbar from "@/components/RightToolbar";

import addOrEditDialog from "./components/addOrEditDialog.vue";
import { InventoryCheckColums } from "@/utils/table/assetsInventoryColums";
import { InventoryCheckStatus } from "@/utils/statuData";

import {
  GetInventoryCheckList,
  AddInventoryCheck,
  getInventoryCheckDetail,
  InventoryCheckFinish,
  InventoryCheckRevoke,
} from "@/api/assetsInventory/billsManage";
import exportButton from "@/components/file/exportButton.vue";
import { GetOrganizationTreeAll } from "@/api/assetsManage/organization";
import { getUserInfo } from "@/utils/auth";
import { ElMessage, ElMessageBox } from "element-plus";
const { proxy } = getCurrentInstance();

const filterInventoryCheckStatus = proxy.getTranslatedOptions(InventoryCheckStatus);
const InventoryCheckData = ref([]); //盘点列表
const loading = ref(false);
const columns = InventoryCheckColums;
const page = reactive({
  total: 0,
  pageNum: 1,
  pageSize: 100,
});
const organizes = ref([]);
const dates = ref(proxy.getDefault30DaysRange());

const handleClearEnableFlag = (value) => {
  value ? value : (searchConfig.value.form.enableFlag = -1);
};
const changeInventorySatus = (value) => {
  searchConfig.value.form.enableFlag = value;
};

const searchConfig = ref({
  form: {
    Dates: dates.value ? dates.value : ["", ""],
    enableFlag: -1,
  },
  formItems: [
    {
      label: t("billsManage.inventoryDocumentStatus"),
      prop: "enableFlag",
      type: "el-select",
      span: 12,
      attrs: {
        clearable: true,
        disabled: false,
        placeholder: t("billsManage.inventoryDocumentStatusPlaceholder"),
      },
      events: {
        change: (value) => changeInventorySatus(value),
        clear: handleClearEnableFlag,
      },
      options: filterInventoryCheckStatus,
      optionProps: {
        key: "id",
        label: "label",
        value: "id",
      },
      filterable: false,
      rules: [
        {
          required: true,
          message: t("billsManage.inventoryDocumentStatusRuleErrorTip"),
          trigger: "change",
        },
      ],
    },
    {
      label: t("billsManage.inventoryDocumentNo"),
      prop: "takeStockNo",
      type: "el-input",
      attrs: {
        clearable: true,
        placeholder: t("billsManage.inventoryDocumentNoPlaceholder"),
      },
    },
    {
      label: t("billsManage.inventoryName"),
      prop: "takeStockName",
      type: "el-input",
      attrs: {
        clearable: true,
        placeholder: t("billsManage.inventoryNamePlaceholder"),
      },
    },

    {
      label: t("billsManage.inventoryOrganization"),
      prop: "takeStockOrganizationId",
      type: "el-tree-select",
      attrs: {
        "check-strictly": true, //任意节点都可以选
        clearable: true,
        placeholder: t("billsManage.inventoryOrganizationPlaceholder"),
      },
      options: organizes,
      optionProps: {
        label: "Label",
        children: "children",
        value: "value",
      },
      events: {},
    },
    {
      label: t("billsManage.inventoryDate"),
      prop: "Dates",
      type: "el-date-picker",
      attrs: {
        valueFormat: "YYYY-MM-DD",
        "range-separator": t("common.to"),
        "start-placeholder": t("common.startDate"),
        "end-placeholder": t("common.endDate"),
        clearable: true,
        type: "daterange",
        "default-time": dates.value,
      },
    },
  ],
  rules: {},
});

const operate = reactive({
  openObj: {
    visible: false,
    openKey: "", //add edit detail
    openType: "", //维修 报废 退还 领用....
    openTitle: "",
    tableTitle: "",
    addLoading: false, //防止重复提交
  },
  formInfo: {
    takeStockOrganizationId: "",
    takeStockName: "",
    remark: "",
  },
  rules: {
    takeStockName: [
      {
        required: true,
        message: t("billsManage.inventoryNameRuleErrorTip"),
        trigger: "blur",
      },
    ],
  },
  organizeOptions: organizes,
  detailInfo: {
    takeStockNo: "",
    ownershipOrganizational: "",
    operationStatus: -1,
  },
  detailLoading: false,
  detailPage: { total: 0, pageNum: 1, pageSize: 100 },
});

//1111获取列表
const queryList = () => {
  const { Dates, ...rest } = searchConfig.value.form;
  const [StartDate, EndDate] = Dates || ["", ""];
  const params = {
    pagination: page.pageNum - 1,
    pageRow: page.pageSize,
    isInit: true,
    ...rest,
    StartDate,
    EndDate,
  };
  loading.value = true;
  GetInventoryCheckList(params)
    .then((res) => {
      loading.value = false;
      InventoryCheckData.value = res.output.output;
      page.total = res.output.count;
    })
    .catch((err) => {
      loading.value = false;
    });
};

//查询单据详情
const queryInventoryCheckDetail = () => {
  operate.detailLoading = true;
  const params = {
    pagination: operate.detailPage.pageNum - 1,
    pageRow: operate.detailPage.pageSize,
    isInit: true,
    ...operate.detailInfo,
  };

  getInventoryCheckDetail(params)
    .then((res) => {
      operate.detailLoading = false;
      operate.tableData = res.output.output;
      operate.detailPage.total = res.output.count;
    })
    .catch((err) => {
      operate.detailLoading = false;
    });
};
//222添加修改相关
const openAddOrEdit = (typeKey, row) => {
  const type = typeKey[0];
  const key = typeKey[1];
  const title =
    key == "add"
      ? t("billsManage.addInventoryDialogTitle")
      : t("billsManage.viewInventoryDialogTitle");
  operate.openObj = {
    visible: true,
    openKey: key,
    openType: type,
    openTitle: title,
    tableTitle: t("billsManage.inventoryAssets"),
    addLoading: false,
  };
  operate.openObj.addLoading = false;
  operate.formInfo = {
    ...row,
  };
  operate.tableData = [];

  if (key != "add") {
    operate.detailInfo = {
      takeStockNo: row.takeStockNo,
      ownershipOrganizational: row.takeStockOrganizationName,
      operationStatus: -1,
    };
    queryInventoryCheckDetail();
  }
};
//完结
const finishInventoryCheck = (row) => {
  const params = {
    takeStockNo: row.takeStockNo,
    userId: JSON.parse(getUserInfo()).userId,
  };
  ElMessageBox.confirm(
    `${t("billsManage.confirmCompleteInventoryDoc")}:${row.takeStockNo}`,
    t("message.tip"),
    {
      confirmButtonText: t("common.confirm"),
      cancelButtonText: t("common.cancel"),
      type: "warning",
    }
  )
    .then(() => {
      InventoryCheckFinish(params)
        .then((res) => {
          console.log(res);
          ElMessage({
            message: t("billsManage.inventoryComplete"),
            type: "success",
          });
          queryList();
        })
        .catch((err) => {
          console.error(err);
        });
    })
    .catch(() => {});
};

//作废盘点单
const revokeReceive = (row) => {
  const params = {
    takeStockNo: row.takeStockNo,
    userId: JSON.parse(getUserInfo()).userId,
  };
  ElMessageBox.confirm(
    `${t("message.confirmVoidDocument")}:${row.takeStockNo}`,
    t("message.tip"),
    {
      confirmButtonText: t("common.confirm"),
      cancelButtonText: t("common.cancel"),
      type: "warning",
    }
  )
    .then(() => {
      InventoryCheckRevoke(params)
        .then((res) => {
          ElMessage({ message: t("message.voidSuccess"), type: "success" });
          queryList();
        })
        .catch((err) => {
          console.log("失败", err);
        });
    })
    .catch(() => {});
};

//获取组织
const queryOrganization = () => {
  GetOrganizationTreeAll("")
    .then((res) => {
      // organizes.value = [res.output]
      organizes.value = res.output;
    })
    .catch((err) => {});
};

//添加盘点单的提交
const submit = async (info) => {
  operate.openObj.addLoading = true;
  let params = {
    createUserId: JSON.parse(getUserInfo()).userId,
    createUser: JSON.parse(getUserInfo()).userName,
    ...info,
  };
  try {
    await AddInventoryCheck({ Info: params }).then((res) => {
      ElMessage({
        message: `${t("billsManage.inventoryDocument")}:${res.output}${t(
          "message.addSuccess"
        )}`,
        type: "success",
      });
    });
    await cancel();
    await queryList();
  } catch (error) {
    operate.openObj.addLoading = false;
  }
};
//取消添加
const cancel = () => {
  operate.openObj.visible = false;
};

///3333高级搜索的
//确定高级搜索
const handleSearch = async (info) => {
  await queryList();
};

onMounted(() => {
  queryList();
  queryOrganization();
});
</script>
<style lang="scss" scoped></style>
